package conchmusic.conchmusicclient.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.adapter.SearchAdapter;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.HistoryInfo;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.util.HistoryResolve;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.PinyinUtils;
import conchmusic.conchmusicclient.view.PlayBar;
import conchmusic.conchmusicclient.view.SearchView;

public class SearchActivity extends AppCompatActivity implements SearchView.SearchViewListener {
    private ListView lvResults;
    private SearchView searchView;
    private ArrayAdapter<String> autoCompleteAdapter;
    private List<Song> dbData;
    private ArrayList<String> autoCompleteData;
    private ArrayList<Song> resultData;
    private static int DEFAULT_HINT_SIZE = 4;
    private static int hintSize = DEFAULT_HINT_SIZE;
    private ArrayList<String> hisArrayList;
    private ArrayList<HistoryInfo> hisInfosList;
    private HistoryResolve historyResolve;
    private ListView historyListView;
    private TextView clearHistory;
    private ArrayAdapter<String> adapter_history;
    private String selectHistory=null;
    private String info=null;
    private View view;
    private ClientControl clientControl;
    private MyDBHelp myDBHelp;
    private SearchAdapter resultAdapter;
    private PlayBar playBar;
    private Button btn_play;
    private Intent intent;
    private String[] list;
    private boolean isOnStart;
    private MyReceiver myReceiver;
    private InitPlayBar initPlayBar;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_search);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        initHistoryData();
        dbData=new ArrayList<>();
        //数据库读localMusics
        myDBHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        dbData=clientControl.findSongs(1);
        //读数据库
        initData();
        initViews();
        isOnStart=true;
    }
    public void initViews(){
        view=findViewById(R.id.history_linearLayout);
        lvResults = (ListView) findViewById(R.id.search_results);
        searchView = (SearchView) findViewById(R.id.search_layout);
        searchView.setSearchViewListener(this);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);
        searchView.setHistoryView(view);
        btn_play=(Button)findViewById(R.id.playbar_play);
        playBar=(PlayBar)findViewById(R.id.local_search_playbar);
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();
        lvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                list=new String[resultData.size()];
                for(int i=0;i<resultData.size();i++){
                    list[i]=Integer.toString(resultData.get(i).getLocalSongId());
                }
                initPlayBar.itemInitPlaybar();
                intent=playMusic(position,list);
                btn_play.setBackgroundResource(R.mipmap.ic_pause);
                startService(intent);
            }
        });
        clearHistory=(TextView)findViewById(R.id.clear_history_textview);
        historyListView=(ListView)findViewById(R.id.history_list);
        clearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyResolve.clearHistory();
                hisArrayList.clear();
                adapter_history.notifyDataSetChanged();
            }
        });
        makeAdapter();
    }
    public void initData() {
        getAutoCompleteData(null);
        getResultData(null);
    }
    public void initHistoryData(){
        hisArrayList=new ArrayList<>();
        historyResolve=new HistoryResolve(this);
        hisInfosList=historyResolve.getHisArrayList();
        for(HistoryInfo hisInfo:hisInfosList){
            hisArrayList.add(hisInfo.getHistory());
        }

    }
    public void makeAdapter(){
        adapter_history = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, hisArrayList);
        historyListView.setAdapter(adapter_history);
        historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectHistory=historyListView.getAdapter().getItem(position).toString();
                info=hisInfosList.get(position).getInfo();
                initLvResult();
            }
        });
    }
    public void initLvResult(){
        if(info==null||selectHistory==null){
            return;
        }else{
            if(info.equals("SearchAction")){
                getResultData(selectHistory);
            }else if(info.equals("ItemOnclick")){
                getCurResultData(selectHistory);
            }
            if(resultData.isEmpty()){
                Toast toast=Toast.makeText(SearchActivity.this,"已被删除",Toast.LENGTH_SHORT);
                toast.show();
            }
            view.setVisibility(View.GONE);
            lvResults.setVisibility(View.VISIBLE);
            lvResults.setAdapter(resultAdapter);
        }
    }
    @Override
    public void onSearch(String text,String flag) {
        view.setVisibility(View.GONE);
        if(flag.equals("SearchAction")){
            getResultData(text);
        }else if(flag.equals("ItemOnclick")){
            getCurResultData(text);
        }

        lvResults.setVisibility(View.VISIBLE);
        if (lvResults.getAdapter() == null) {
            lvResults.setAdapter(resultAdapter);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onRefreshAutoComplete(String text) {
        if("".equals(text)){
            autoCompleteData.clear();
            autoCompleteAdapter.notifyDataSetChanged();
        }else{
            getAutoCompleteData(text);
        }
    }

    @Override
    public void clearResult() {
        autoCompleteData.clear();
        lvResults.setVisibility(View.GONE);
    }


    private void getResultData(String text) {
        String textPinYin=PinyinUtils.getPingYin(text).toUpperCase();
        int textLength=textPinYin.length();
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            for (int i = 0; i < dbData.size(); i++) {
                String songName=dbData.get(i).getTitle();
                String pinyin= PinyinUtils.getPingYin(songName).toUpperCase();
                if(pinyin.length()>=textLength){
                    if(pinyin.contains(textPinYin)) resultData.add(dbData.get(i));
                }else{
                    if(textPinYin.contains(pinyin)) resultData.add(dbData.get(i));
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }
    public void getCurResultData(String text){
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            for (int i = 0; i < dbData.size(); i++) {
                if (dbData.get(i).getTitle().equals(text.trim())) {
                    resultData.add(dbData.get(i));
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }
    private void getAutoCompleteData(String text) {
        String textPinYin=PinyinUtils.getPingYin(text).toUpperCase();
        int textLength=textPinYin.length();
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<String>(6);
        } else {
            autoCompleteData.clear();
            for (int i = 0,size=0; i < dbData.size()&&size<6; i++) {
                String songName=dbData.get(i).getTitle();
                String pinyin= PinyinUtils.getPingYin(songName).toUpperCase();
                if(pinyin.length()>=textLength){
                    if(pinyin.contains(textPinYin))
                    {
                        autoCompleteData.add(dbData.get(i).getTitle());
                        size++;
                    }
                }else{
                    if(textPinYin.contains(pinyin)){
                        autoCompleteData.add(dbData.get(i).getTitle());
                        size++;
                    }
                }

            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteData);
        } else {
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }
    public void notifyLocalMusic(){
        dbData=clientControl.findSongs(1);
        for(Song song:dbData){
            Log.i("song",song.getTitle());
        }
    }
    public Intent playMusic(int position,String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","play");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(SearchActivity.this.getPackageName());
        return intent;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isOnStart){
            isOnStart=false;
        }else {
            dbData=clientControl.findSongs(1);
        }
        playBar.startMsgReceiver();
        myReceiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("conchmusic.conchmusicclient.downloadsuccess");
        SearchActivity.this.registerReceiver(myReceiver,filter);
    }

    @Override
    protected void onPause() {
        try {
            super.onPause();
        } catch (Exception e) {
            e.printStackTrace();
        }
        unregisterReceiver(myReceiver);
        playBar.closeMsgReceiver();
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            String info=bundle.getString("download");
            if(info.equals("success")){
                dbData=clientControl.findSongs(1);
            }
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        SearchActivity.this.finish();
    }
    public void closeActivity(){
        SearchActivity.this.onDestroy();
    }
}
